<?php
/**
* @file CommonService.php
* Copyright (c) Friends Group. All rights reserved.
* $Id$
*
*/

require_once(realpath(dirname(__FILE__)) . '/classes/Account.php');
require_once(realpath(dirname(__FILE__)) . '/classes/UserOption.php');
require_once(realpath(dirname(__FILE__)) . '/classes/UserChatOption.php');
require_once(realpath(dirname(__FILE__)) . '/classes/Avatar.php');
require_once(realpath(dirname(__FILE__)) . '/classes/Role.php');
require_once(realpath(dirname(__FILE__)) . '/common/ServiceFactory.php');
require_once(realpath(dirname(__FILE__)) . '/common/Utilities.php');


class CommonService
{

    function __construct()
    {
        $this -> repo = new DataService();
    }
    
    public function countUserByRole($role)
    {
        return count($this -> repo -> getList("SELECT id FROM Account WHERE roleID = '{$role -> getID()}' AND activationKey IS NULL", "Account"));
    }
    
    public function getAllRoles()
    {
        return $this -> repo -> getList("SELECT * FROM Role", "Role");
    }
    
    public function getAllUsers()
    {
        return $this -> repo -> getList("SELECT * FROM Account WHERE activationKey IS NULL", "Account");
    }
    
    public function getDefaultAvatars($start = 0, $all = false)
    {
        $limit = "";
        if(!$all)
            $limit =  "LIMIT $start,10";
        
        return $this -> repo -> getList("SELECT * FROM Avatar WHERE picture LIKE 'default%' ORDER BY ID $limit", "Avatar");
    }
    
    public function getAllAvatarsUploadedByUser($username, $start = 0, $all = false)
    {
        $limit = "";
        if(!$all)
            $limit =  "LIMIT $start,10";
        
        return $this -> repo -> getList("SELECT * FROM Avatar WHERE picture LIKE '$username%' ORDER BY ID $limit", "Avatar");
    }
    
    public function getAvatarByName($avatarName)
    {
        return $this -> repo -> getFirst("SELECT * FROM Avatar WHERE picture = '{$avatarName}'", "Avatar");
    }
    
    public function getAllMessageTypes()
    {
        return $this -> repo -> getList("SELECT * FROM MessageType", "MessageType");
    }
    
    public function getStatusByName($statusName)
    {
        $status = $this -> repo -> getFirst("SELECT * FROM Status WHERE status = '$statusName'", "Status");
        if($status == null)
            $status = $this -> repo -> getFirst("SELECT * FROM Status WHERE status = 'Custom'", "Status");
        
        return $status;
    }
    
    public function getUsersByRole($role)
    {
        if($role == null)
            return $this -> getAllUsers();
        
        return $this -> repo -> getList("SELECT * FROM Account WHERE roleID = '{$role -> getID()}' AND activationKey IS NULL", "Account");
    }
    
    public function getRoleByName($roleName)
    {
        return $this -> repo -> getFirst("SELECT * FROM Role WHERE roleName = '{$roleName}'", "Role");
    }
    
    public function getMessageTypeByName($messageTypeName)
    {
        return $this -> repo -> getFirst("SELECT * FROM MessageType WHERE MessageType = '{$messageTypeName}'", "MessageType");
    }
    
    public function canDeleteAvatar($avatarId)
    {
        $u = $this -> repo -> getFirst("SELECT * FROM Account WHERE AvatarID = '$avatarId'", "Account");
        $a = $this -> repo -> getFirst("SELECT * FROM Avatar WHERE ID = '$avatarId'", "Avatar");
        return $u == null && preg_match('/^default+/', $a -> getPicture());
    }
    
    public function getAvatarSrc($avatarId, $size = 1)
    {
        $avatar = $this -> repo -> getFirst("SELECT * FROM Avatar WHERE id = '$avatarId'", "Avatar");
        if($avatar != null)
            $image = $this -> getPictureBySize($avatar -> getPicture(), $size);
        else
            $image = $this -> getPictureBySize("default-avatar.gif", 2);
        
        $st = ServiceFactory::get("SystemConfiguration");
        return $st -> getSetting("site-url") . "/" . $st -> getSetting("avatar-path") . "/" . $image;
    }
    
    public function  getPictureBySize($name, $size)
    {
        $st = ServiceFactory::get("SystemConfiguration");
        $path = realpath(dirname(__FILE__)) . "/../" . $st -> getSetting("avatar-path") . "/";
        
        $extension =  "." . end(explode(".", $name));
        $newName = substr($name, 0, -strlen($extension));
        
        if($size == 1)
        {
            $newName = $newName . "-" . $st -> getSetting("small-avatar-size");
            $size = split("x", $st -> getSetting("small-avatar-size"));

        }
        elseif($size == 2)
        {
            $newName = $newName . "-" .  $st -> getSetting("medium-avatar-size");
            $size = split("x", $st -> getSetting("medium-avatar-size"));
        }
        elseif($size == 3)
        {
            $newName = $newName . "-" .  $st -> getSetting("large-avatar-size");
            $size = split("x", $st -> getSetting("large-avatar-size"));
        }
        
        $newName = $newName . $extension;
        
        if(file_exists($path . $name))
        {
            $imageresized = ImageResize::resize($path .  $name, $size[0], $size[1]);
            imagejpeg($imageresized, $path . $newName);
            return $newName;
        }
        
        return $name;
    }
    
    function uploadAvatar($username = "default", $uploadName = "upload-avatar")
    {
        $st = ServiceFactory::get("SystemConfiguration");
        $path_avatars = realpath(dirname(__FILE__)) . "/../" . $st -> getSetting("avatar-path") . "/";
        
        $limitedext = array(".gif",".jpg",".png",".jpeg");
        
        $file_type = $_FILES[$uploadName]['type'];
        $file_name = $_FILES[$uploadName]['name'];
        $file_size = $_FILES[$uploadName]['size'];
        $file_tmp = $_FILES[$uploadName]['tmp_name'];
        
        if($file_size > $st -> getSetting("upload-avatar-size"))
            throw new Exception("Kích thước file quá lớn, tối đa là {$st -> getSetting("upload-avatar-size")}");
        
        $ext =  "." . end(explode(".", $file_name));
        $ext = strtolower($ext);
        
        if (!in_array($ext, $limitedext)) 
        {
            throw new Exception("Định dạng không được hỗ trợ, chỉ hỗ trợ GIF, JPG, PNG, JPEG");
        }
        
        $getExt = explode ('.', $file_name);
        $file_ext = $getExt[count($getExt)-1];
        $rand_name = md5(time());
        
        $newName = $username . "-" . $rand_name . "." . $file_ext;
        
        if(!move_uploaded_file ($file_tmp, $path_avatars . $newName))
            throw new Exception("Không thể upload file $file_name");
        
        return $newName;
    }
    
    function cmp($a, $b)
    {
        return strlen($a) < strlen($b);
    }
    
    public function getAllEmotesTheme($oneone = true)
    {
        $st = ServiceFactory::get("SystemConfiguration");
        $path = realpath(dirname(__FILE__)) . "/../" . $st -> getSetting("emoticon-path") . "/";
        
        if (!is_dir($path))
            return false;
        
        $themes = array();
        
        if ($handle = @opendir($path))
        {
            while (false !== ($file = @readdir($handle)))
            {
                $theme = array();
                if (is_dir($path.'/'.$file)) 
                {
                    if ($file != '..' && $file != '.' && $file != '')
                    {
                        if(file_exists($path.'/'.$file . '/theme'))
                        {
                            $text = fread( fopen( $path.'/'.$file . '/theme', 'r' ), filesize( $path.'/'.$file . '/theme' ));
                            if(!empty($text))
                            {
                                $if = split("\n", $text);
                                if(count($if))
                                {
                                    $emotes = array();
                                    foreach ($if as $line)
                                    {
                                        $line = trim(preg_replace('/(\[.+\]|[\r\n])/', '', $line));
                                        $line = preg_replace('/\s+/', ' ', $line);
                                        if(!empty($line) && $line[0] != "#")
                                        {
                                            $li = split("=", $line);
                                            if(count($li) > 1 && ($li[0] == "Key" || $li[0] == "Name" || $li[0] == "Description" || $li[0] == "Icon" || $li[0] == "Author"))
                                            {
                                                $theme[$li[0]] = $li[1];
                                            }
                                            else
                                            {
                                                $li = split(" ", $line);
                                                if(count($li) > 1)
                                                {
                                                    if(!$oneone)
                                                    {
                                                        for($k = 1; $k < count($li); $k++)
                                                        {
                                                            $li[$k] = trim($li[$k], " ");
                                                            if(!strpos($emotes[$li[0]], $li[$k]) && !empty($li[$k]))
                                                                $emotes[$li[0]] = $emotes[$li[0]] . " " . $li[$k];
                                                        }
                                                    }
                                                    else
                                                        $emotes[$li[0]] = $li[1] . " ";
                                                }
                                                if(!$oneone)
                                                    $emotes[$li[0]] = $emotes[$li[0]] . " ";
                                            }
                                        }
                                    }
                                    if($oneone)
                                        uasort($emotes, array($this, "cmp"));
                                    
                                    $theme["Emotes"] = $emotes;
                                }
                            }
                            $themes[$file] = $theme;
                        }
                    }
                }
            }
            
            closedir($handle);
            return $themes;
        }
    }
    
    function replace_callback($ma)
    {
        return substr(str_replace(' ', '', $ma[0]),1,-1);
    }
    
    function replaceEmoticon($string, $emotestheme)
    {
        $string = " ".$string." ";
        $st = ServiceFactory::get("SystemConfiguration");
        $bpath = $st -> getSetting("site-url") . "/" . $st -> getSetting("emoticon-path") . "/" . $emotestheme;
        
        $includeFile = realpath(dirname(__FILE__)) . "/../" . $st -> getSetting("emoticon-path") . "/" . $emotestheme . "/emotes.php";
        if(file_exists($includeFile))
            include($includeFile);
        else
            throw new Exception("Không tìm thấy file $includeFile");
        
        foreach($emotes_array as $key => $value)
        {
            $value = trim($value);
            $path = $bpath . "/" . $key;
            $a = "";
            for($i = 0; $i < strlen($value); $i++)
            {
                $a = $a . $value[$i] . " ";
            }
            $replace = "<img alt='{{$a}}' title='{{$a}}' src='$path' />";
            $string = str_replace($value, "$replace", $string);
            $string = str_replace(strtolower($value), "$replace", $string);
        }
        return preg_replace_callback('/{.[^{]+}/i', array($this, "replace_callback"), $string);
    }
    
    function generateEmoticonArray($themeKey)
    {
        $em = CommonService::getAllEmotesTheme();
        $st = ServiceFactory::get("SystemConfiguration");
        $f = fopen(realpath(dirname(__FILE__)) . "/../" . $st -> getSetting("emoticon-path") . "/" . $themeKey . "/emotes.php", "w+");
        fwrite($f, "<?php\r\n/**\r\n* @file emotes.php\r\n* Copyright (c) Friends Group. All rights reserved.\r\n* \$Id$\r\n*\r\n*/\r\n\r\n");
        fwrite($f, "//++Autogenerated -- start of section automatically generated from Nowchat.emotes");
        foreach ($em as $k => $v)
        {
            if($v['Key'] == $themeKey)
            {
                fwrite($f, "\r\n/*\r\n\tName: " . $v['Name'] . "\r\n\tDescription: " . $v['Description'] . "\r\n\tAuthor: " . $v['Author'] . "\r\n*/");
                fwrite($f, "\r\n\$emotes_array = array(\r\n ");
                foreach ($v['Emotes'] as $k1 => $v1)
                {
                    fwrite($f, "\t\t\"" . $k1 . "\" => \"" . preg_replace('/"/', '\\"', $v1) . "\",\r\n");
                }
                fwrite($f, ");\r\n");
            }
        }
        fwrite($f, "//++Autogenerated -- end of section automatically generated from Nowchat.emotes");
        fwrite($f, "\r\n?>\r\n");
        fclose($f);
    }
}

?>